package com._21cn.cms.site.web.controller;

import com._21cn.cms.common.Constants;
import com._21cn.cms.common.FormSelector;
import com._21cn.cms.site.entity.Channel;
import com._21cn.cms.site.entity.Column;
import com._21cn.cms.site.entity.Site;
import com._21cn.cms.site.service.ChannelService;
import com._21cn.cms.site.service.ColumnService;

import com._21cn.cms.site.service.SiteService;
import com._21cn.cms.template.entity.Template;
import com._21cn.cms.template.service.TemplateService;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/site/column")
public class ColumnController extends BaseController{

	private static String listView = "/admin/site/column/list";
    private static String showView = "/admin/site/column/show";
    private static String jsonView = "/admin/site/column/json";
    private static String formView = "/admin/site/column/form";
    private static String redirectListView = "redirect:/admin/site/column/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private TemplateService templateService;
	
	@Autowired(required = false)
    @Qualifier("columnValidator")
    private Validator columnValidator;

    @RequestMapping("/list")
    public String listColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        setRequestModelMap( request, model, true );
        model.addAttribute( "statusMap", FormSelector.getStatusMap() );
        model.addAttribute("isShowMap", FormSelector.getIsShowMap());
        return view;
    }

    @RequestMapping("/search")
    public String searchColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        Integer select = reqInfo.getIntParameter("select", 0);
        setRequestModelMap( request, model, true );

        if(select.equals(1)){  //请求类型  1 接口、0普通
            Map<String, Object> resultMap = new HashMap<String,Object>();
            String ids = reqInfo.getParameter("ids", null);
            List<Integer> idList = StringUtil.str2IntList(ids);
            if( idList.size()>0 ){
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("inIdList", idList);
                params.put("eqStatus", Constants.STATUS_ENABLE);
                List<Column> list = columnService.getList(params, Constants.DEFAULT_FIRST_PAGE_NO, Constants.DEFAULT_PAGE_SIZE_COMMON);
                for(Column column : list){
                    resultMap.put(column.getId()+"", column.getName());
                }
            }
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(resultMap) );
            return view;
        }else {
            model.addAttribute("orderByClause", "IS_SHOW desc,ID desc");
            PageList<Column> result = getPageList( model );
            for(Column column: result){
                Site site = siteService.getById(column.getSiteId());
                if( site!=null ){
                    column.setSiteName(site.getName());
                }
                Channel channel = channelService.getById(column.getChannelId());
                if( channel!=null ){
                    column.setChannelName(channel.getName());
                }
                Column parentColumn = columnService.getById(column.getParentId());
                if( parentColumn!=null ){
                    column.setParentColumnName(parentColumn.getParentColumnName());
                }
                if (column.getListTemplateId().intValue() > 0) {
                    Template template = (Template)this.templateService.getById(column.getListTemplateId());
                    if (template != null) {
                        column.setTemplateName(template.getName());
                    }
                }
            }
            model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
            return view;
        }
    }

    @RequestMapping("/show")
    public String showColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Column column = columnService.getById( id );
            if( column == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
//            model.addAttribute( "statusMap", FormSelector.getStatusMap());
            model.addAttribute( "column", column );
        }
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/edit")
    public String editColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Column column = new Column();
        if( id > 0 ){
            column = columnService.getById(id);
            if( column == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
        }
        model.addAttribute("column", column );
        model.addAttribute("statusMap", FormSelector.getStatusMap());
        model.addAttribute("isShowMap", FormSelector.getIsShowMap());
        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping({"/save"})
    public String saveColumn(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        if (id.intValue() > 0) {
            Column column = this.columnService.getById(id);
            if (bind(request, column, model, new Validator[] { this.columnValidator }).hasErrors()) {
                return formView;
            }
            column = setExtProperties(column);
            Column obj = this.columnService.getColumnByUrl(column.getUrl());
            if ((!column.getId().equals(obj.getId())) &&
                    (column.getUrl().equals(obj.getUrl()))) {
                model.put("error.param.wrong", "栏目url已经存在，请重新输入代号");
                model.put("column", column);
                return formView;
            }

            this.columnService.update(column);
        } else {
            Column column = new Column();
            if (bind(request, column, model, new Validator[] { this.columnValidator }).hasErrors()) {
                return formView;
            }
            column = setExtProperties(column);

            Column obj = this.columnService.getColumnByUrl(column.getUrl());
            if (obj != null) {
                model.put("error.param.wrong", "栏目url已经存在，请重新输入代号");
                model.put("column", column);
                return formView;
            }
            this.columnService.insert(column);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    private Column setExtProperties(Column column) {
        column.setModifyTime(new Date());
        String code = column.getCode();
        Integer parentId = column.getParentId();
        if (parentId.intValue() > 0) {
            Column parentColumn = this.columnService.getById(parentId);
            String path = parentColumn.getPath() + "/" + code;
            column.setPath(path);
            String url = parentColumn.getUrl() + "/" + code;
            column.setUrl(url);
        } else {
            Integer channelId = column.getChannelId();
            Channel channel = this.channelService.getById(channelId);
            String path = channel.getPath() + "/" + code;
            column.setPath(path);
            String url = channel.getUrl() + "/" + code;
            column.setUrl(url);
        }
        return column;
    }
	
	@RequestMapping("/updateStatus")
    public String updateColumnStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            columnService.update( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/delete")
    public String deleteColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            columnService.delete( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/select")
    public String selectColumn(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Column> result = getPageList( model );
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result) );
        return view;
    }
	
	private PageList<Column> getPageList(ModelMap model) {
        if(model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());
        PageList<Column> columnList = columnService.getList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()) );
        model.addAttribute( "columnList", columnList);
        model.addAttribute( "objList", columnList);
        model.addAttribute( "pageTurn", columnList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return columnList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "siteId", "siteId" );
			propertyTitleMap.put( "channelId", "channelId" );
			propertyTitleMap.put( "parentId", "parentId" );
			propertyTitleMap.put( "name", "name" );
			propertyTitleMap.put( "code", "code" );
			propertyTitleMap.put( "path", "path" );
			propertyTitleMap.put( "url", "url" );
			propertyTitleMap.put( "metaKeyword", "metaKeyword" );
			propertyTitleMap.put( "metaDescription", "metaDescription" );
			propertyTitleMap.put( "memo", "memo" );
			propertyTitleMap.put( "status", "status" );
			propertyTitleMap.put( "listTemplateId", "listTemplateId" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "createUserId", "createUserId" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
			propertyTitleMap.put( "modifyUserId", "modifyUserId" );
        }
        return propertyTitleMap;
    }
}
